﻿using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudStorageLight.Core
{
    public static class PdfCryptoUtil
    {
        /// <summary>
        /// パスワードを付与する
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="password"></param>
        public static void SetPassword(string filePath, string password)
        {
            var outPdf = Path.GetTempFileName();
            try
            {
                using (Stream input = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (Stream output = new FileStream(outPdf, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        iTextSharp.text.pdf.PdfReader tempReader = new iTextSharp.text.pdf.PdfReader(input);
                        iTextSharp.text.pdf.PdfEncryptor.Encrypt(tempReader, output, true, password, password, iTextSharp.text.pdf.PdfWriter.ALLOW_SCREENREADERS);
                        tempReader.Close();
                    }
                }
                File.Copy(outPdf, filePath, true);

            }
            finally
            {
                File.Delete(outPdf);
            }
        }

        public static void Decrypto(string filePath, string password)
        {
            var outPdf = Path.GetTempFileName();
            try
            {
                using (Stream input = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (Stream output = new FileStream(outPdf, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        iTextSharp.text.pdf.PdfReader tempReader = new iTextSharp.text.pdf.PdfReader(input, new System.Text.ASCIIEncoding().GetBytes(password));
                        PdfStamper stamper = new PdfStamper(tempReader, output);
                        stamper.Close();
                        tempReader.Close();
                    }
                }
                File.Copy(outPdf, filePath, true);
            }
            finally
            {
                File.Delete(outPdf);
            }
        }

        public static bool IsPasswordProtected(string pdfFullname)
        {
            try
            {
                PdfReader pdfReader = new PdfReader(pdfFullname);
                return pdfReader.IsEncrypted();
            }
            catch (BadPasswordException)
            {
                return true;
            }
        }
    }
}
